<template>
  <!-- <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['label:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['label:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['label:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['label:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="模板对象" align="center" prop="template" />
      <el-table-column label="分类说明" align="center" prop="description" />
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['label:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['label:template:remove']"
          >删除</el-button>
        </template>
</el-table-column>
</el-table>

<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
  @pagination="getList" />

<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="模板名称" prop="templateName">
      <el-input v-model="form.templateName" placeholder="请输入模板名称" />
    </el-form-item>
    <el-form-item label="模板对象" prop="template">
      <el-input v-model="form.template" type="textarea" placeholder="请输入内容" />
    </el-form-item>
    <el-form-item label="分类说明" prop="description">
      <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submitForm">确 定</el-button>
    <el-button @click="cancel">取 消</el-button>
  </div>
</el-dialog>
</div> -->

  <div class="flex-col">
    <div class="flex-row justify-center" style="margin: 10px 0">
      <!-- 纸张大小 A3、A4 等 -->
      <div class="paper">
        <el-select v-model="curPaperType" @change="handlePaperTypeChange" placeholder="纸张大小">
          <el-option v-for="(value, type) in paperTypes" :key="type" :label="type" :value="type">
          </el-option>
          <el-option label="自定义" value="customSize" @click.native="handleCustomClick"> </el-option>
        </el-select>
        <!-- 自定义尺寸弹窗 -->
        <el-dialog title="自定义纸张尺寸" :visible.sync="customDialogVisible" width="30%">
          <el-form :model="customSize">
            <el-form-item label="宽度(mm)">
              <el-input-number v-model="customSize.width" :min="1" :step="1" />
            </el-form-item>
            <el-form-item label="高度(mm)">
              <el-input-number v-model="customSize.height" :min="1" :step="1" />
            </el-form-item>
          </el-form>
          <span slot="footer">
            <el-button @click="customDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="setPaper(customSize.width, customSize.height)">确定</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- 缩放 -->
      <div class="flex-row align-center ml-10">
        <button class="info circle-10" @click="changeScale(false)"><i class="iconfont sv-zoom-out" /></button>
        <div style="margin: 0 4px; width: 40px">{{ (scaleValue * 100).toFixed(0) }}%</div>
        <button class="info circle-10" @click="changeScale(true)"><i class="iconfont sv-zoom-in" /></button>
      </div>
      <button class="api circle-10 ml-10" @click.stop="rotatePaper">
        <i class="iconfont sv-rotate" />
        旋转纸张(宽高互换)
      </button>
      <button class="api circle-10 ml-10" @click.stop="clearPaper">
        <i class="iconfont sv-clear" />
        清空纸张
      </button>
      <button class="api circle-10 ml-10" @click.stop="exportJson">
        <i class="iconfont sv-export" />
        导出模板 json
      </button>
      <button class="api circle-10 ml-10" @click.stop="exportJsonTid">
        导出模板 json tid
        <i class="iconfont sv-export" />
      </button>
      <button class="secondary circle-10 ml-10" @click.stop="print">
        <i class="iconfont sv-printer" />
        浏览器打印
      </button>
      <button class="warning circle-10 ml-10" @click.stop="print2">
        直接打印(需要连接客户端)
        <i class="iconfont sv-printer" />
      </button>
    </div>
    <div class="flex-row" style="height: 87vh">
      <div class="flex-2 left">
        <div class="flex-row justify-center flex-wrap">
          <div class="title">基础元素</div>
          <div class="ep-draggable-item item" tid="baseModule.text">
            <i class="iconfont sv-text" />
            <span>文本</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.image">
            <i class="iconfont sv-image" />
            <span>图片</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.longText">
            <i class="iconfont sv-longText" />
            <span>长文</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.table">
            <i class="iconfont sv-table" />
            <span>表格</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.barcode">
            <i class="iconfont sv-barcode" />
            <span>条形码</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.qrcode">
            <i class="iconfont sv-qrcode" />
            <span>二维码</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.hline">
            <i class="iconfont sv-hline" />
            <span>横线</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.vline">
            <i class="iconfont sv-vline" />
            <span>竖线</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.rect">
            <i class="iconfont sv-rect" />
            <span>矩形</span>
          </div>
          <div class="ep-draggable-item item" tid="baseModule.oval">
            <i class="iconfont sv-oval" />
            <span>圆形</span>
          </div>
        </div>
      </div>
      <div class="flex-5 center">
        <!-- 设计器的 容器 -->
        <div id="hiprint-printTemplate">

        </div>

      </div>
      <div class="flex-2 right">
        <!-- 元素参数的 容器 -->
        <div id="PrintElementOptionSetting"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/label/template"
import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint";
import { baseProvider } from "./baseProvider";

export default {
  name: "Template",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标签模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        template: null,
        description: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        template: [
          { required: true, message: "模板对象不能为空", trigger: "blur" }
        ],
      },
      curPaperType: "",
      curPaper: {
        type: "A4",
        width: 210,
        height: 296.6,
      },
      paperTypes: {
        A3: {
          width: 420,
          height: 296.6,
        },
        A4: {
          width: 210,
          height: 296.6,
        },
        A5: {
          width: 210,
          height: 147.6,
        },
        B3: {
          width: 500,
          height: 352.6,
        },
        B4: {
          width: 250,
          height: 352.6,
        },
        B5: {
          width: 250,
          height: 175.6,
        },
      },
      customSize: {
        width: 210,   // 默认宽度
        height: 296.6  // 默认高度
      },
      // 自定义纸张
      customDialogVisible: false,
      paperWidth: "220",
      paperHeight: "80",
      scaleValue: 1,
      scaleMax: 5,
      scaleMin: 0.5,
      hiprintTemplate: {},
      options: {
        config: {
        }
      }
    };

  },
  created() {
    // this.getList();
  },
  mounted() {
    // 初始化 provider
    hiprint.init({
      providers: [baseProvider(this.options)],
    });
    this.buildLeftElement();
    this.buildDesigner();
  },
  methods: {
    /**
    * 获取标签模板列表
    * 构建左侧可拖拽元素
    * 注意: 可拖拽元素必须在 hiprint.init() 之后调用
    * 而且 必须包含 class="ep-draggable-item" 否则无法拖拽进设计器
    */
    buildLeftElement() {
      hiprint.PrintElementTypeManager.buildByHtml($(".ep-draggable-item"));
    },
    buildDesigner() {
      // eslint-disable-next-line no-undef
      $("#hiprint-printTemplate").empty(); // 先清空, 避免重复构建
      this.hiprintTemplate = new hiprint.PrintTemplate({
        settingContainer: "#PrintElementOptionSetting", // 元素参数容器
        onImageChooseClick: (target) => {
          // 创建文件输入元素
          const fileInput = document.createElement('input');
          fileInput.type = 'file';
          fileInput.accept = 'image/*'; // 限制图片类型
          fileInput.style.display = 'none'; // 隐藏原生控件
          // 文件选择回调
          fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            // 使用FileReader读取文件
            const reader = new FileReader();
            reader.onload = (event) => {
              // 获取base64数据
              const imageDataUrl = event.target.result;

              // 更新图片元素（保持原有配置）
              target.refresh(imageDataUrl, {
                auto: true, // 根据图片宽高自动等比(宽>高?width:height)
                // width: true, // 按宽调整高
                // height: true, // 按高调整宽
                // real: true // 维持实际尺寸渲染
              });
            };

            // 读取文件为DataUrl
            reader.readAsDataURL(file);
          });
          // 触发文件选择
          document.body.appendChild(fileInput);
          fileInput.click();

          // 清理DOM
          fileInput.addEventListener('click', () => {
            document.body.removeChild(fileInput);
          });
          // target.getValue()
          // target.refresh(url)
        }
      });
      // 构建 并填充到 容器中
      // 可以先 console.log($("#hiprint-printTemplate")) 看看是否有该 dom
      this.hiprintTemplate.design("#hiprint-printTemplate", { grid: true });
    },
    // 浏览器打印
    print() {
      let json = this.hiprintTemplate.getJson();
      console.log(json);
      let printData = { name: "CcSimple" };
      let html = this.hiprintTemplate.getHtml(printData);
      console.log(html);
      // alert("导出成功! 请查看控制台输出");
      // 打印数据，key 对应 元素的 字段名
      // 参数: 打印时设置 左偏移量，上偏移量
      let options = { leftOffset: -1, topOffset: -1 };
      // 扩展
      let ext = {
        callback: () => {
          console.log("浏览器打印窗口已打开");
        },
        styleHandler: () => {
          // 重写 文本 打印样式
          // return "<style>.hiprint-printElement-text{color:red !important;}</style>";
          return "";
        },
      };
      // 调用浏览器打印
      this.hiprintTemplate.print(printData, options, ext);
    },
    /**
     * 直接打印: 借助客户端,静默打印(无弹窗直接打印)
     * 注意: 需要先连接客户端
     */
    print2() {
      if (hiprint.hiwebSocket.opened) {
        this.hiprintTemplate.print2({});
      } else {
        alert("请先连接客户端(刷新网页), 然后再点击「直接打印」");
      }
    },
    // ----------------- 模板对象 api 部分 -----------------
    /**
     * 旋转纸张
     */
    rotatePaper() {
      this.hiprintTemplate.rotatePaper();
    },
    /**
     * 清空所有元素
     */
    clearPaper() {
      this.hiprintTemplate.clear();
    },
    /**
     * 导出模板 json
     * 必须确保 hiprintTemplate 已成功创建
     */
    exportJson() {
      let json = this.hiprintTemplate.getJson();
      console.log(json);
      alert("导出成功! 请查看控制台输出");
    },
    /**
     * 导出模板 json tid
     * 仅导出 options, 不导出 printElementType
     * 必须确保 hiprintTemplate 已成功创建
     */
    exportJsonTid() {
      let json = this.hiprintTemplate.getJsonTid();
      console.log(json);
      alert("导出成功! 请查看控制台输出");
    },
    // 方法
    showPaperPop() {
      this.paperPopVisible = true;
    },
    hidePaperPop() {
      this.paperPopVisible = false;
    },
    handleCustomClick(event) {
      event.stopPropagation();
      this.customDialogVisible = true;
      this.curPaperType = 'customSize';
    },
    // 处理纸张类型变更
    handlePaperTypeChange(type) {
      if (type != 'customSize') {
        this.setPaper(
          this.paperTypes[type].width,
          this.paperTypes[type].height
        );
      }
    },

    // 设置纸张尺寸（核心方法）
    setPaper(width, height) {
      // 实际项目中这里可能触发其他逻辑：
      // - 更新Vuex状态
      // - 通知父组件尺寸变化
      // - 更新本地存储的尺寸配置
      console.log('设置纸张尺寸为:', width, 'x', height);

      // 关闭弹窗
      this.customDialogVisible = false;
      try {
        this.hiprintTemplate.setPaper(width, height);
      } catch (error) {
        alert(`操作失败: ${error}`);
      }
      // 可选：保存到本地存储
      // localStorage.setItem('customPaperSize', JSON.stringify({width, height}));
    },
    setPaperOther() {
      let value = {};
      value.width = this.paperWidth;
      value.height = this.paperHeight;
      this.paperPopVisible = false;
      setPaper("other", value);
    },
    changeScale(big) {
      let newScaleValue = this.scaleValue;
      if (big) {
        newScaleValue += 0.1;
        if (newScaleValue > this.scaleMax) newScaleValue = 5;
      } else {
        newScaleValue -= 0.1;
        if (newScaleValue < this.scaleMin) newScaleValue = 0.5;
      }
      if (this.hiprintTemplate) {
        // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
        this.hiprintTemplate.zoom(newScaleValue);
        this.scaleValue = newScaleValue;
      }
    }
  }
}
</script>
<style>
/* 重写全局 hiprint 样式 */
.hiprint-headerLine,
.hiprint-footerLine {
  border-color: purple !important;
}

.hiprint-headerLine:hover,
.hiprint-footerLine:hover {
  border-top: 3px dashed purple !important;
}

.hiprint-headerLine:hover:before {
  content: "页眉线";
  left: calc(50% - 18px);
  position: relative;
  background: #ffff;
  top: -14px;
  color: purple;
  font-size: 12px;
}

.hiprint-footerLine:hover:before {
  content: "页脚线";
  left: calc(50% - 18px);
  position: relative;
  color: purple;
  background: #ffff;
  top: -14px;
  font-size: 12px;
}
</style>
<style scoped>
/* 区域 */
.left {
  background: white;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  padding: 10px 0;
  box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
  overflow: auto;
}

.center {
  margin: 0 10px;
  background: white;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  padding: 20px;
  box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
  overflow: auto;
}

.right {
  background: white;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  padding: 10px 0;
  box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
  overflow: auto;
}

/* 左侧拖拽元素样式 */
.title {
  font-size: 16px;
  font-weight: 500;
  width: 100%;
  margin: 10px 0 0 24px;
}

.item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: white;
  padding: 4px 10px;
  margin: 10px 8px 4px 8px;
  width: 38%;
  min-height: 60px;
  border-radius: 4px;
  box-shadow: 2px 2px 2px 2px rgba(171, 171, 171, 0.2);
}

.item .iconfont {
  font-size: 1.5rem;
}

.item span {
  font-size: 14px;
}
</style>
